package com.ly.report_ah.sercive.master.impl;

import com.ly.report_ah.dao.master.ReportMapper;
import com.ly.report_ah.dao.master.SmpSummaryMapper;
import com.ly.report_ah.entity.master.SmpSummary;
import com.ly.report_ah.sercive.master.DatService;
import com.ly.report_ah.sercive.master.ReportService;
import com.ly.report_ah.util.ConstatUtil;
import com.ly.report_ah.vo.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ly.report_ah.sercive.master.impl.DatServiceImpl.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {


    @Resource
    private ReportMapper reportMapper;

    @Resource
    private DatService datService;

    /**
     * 结果表
     */
    @Resource
    private SmpSummaryMapper smpSummaryMapper;

    @Autowired
    private ConstatUtil constatUtil;


    @Override
    public ReportVO getReportVO(String company_id, Long yearMonth,String type) {
        return ReportVO.builder()
                .transformer110(this.getReportPartVo(company_id, "DFPowerTransformer", "110",type))
                .transformer35(this.getReportPartVo(company_id, "DFPowerTransformer", "35",type))
                .line110(this.getReportPartVo(company_id, "DFLine", "110",type))
                .line35(this.getReportPartVo(company_id, "DFLine", "35",type))
                .distributionLine(this.getReportPartVo(company_id, "DFDistributionLine", "10",type))
                .distributionTransformer(this.getReportPartVo(company_id, "DFDistributionTransformer", "10",type))
                .build();
    }

    @Override
    public ReportPartVO getReportPartVo(String company_id, String typecode, String voltage,String type) {

        //1，组装汇总表
        List<SmpSummary> summaryData = reportMapper.getSummaryData(company_id, typecode, voltage);
        List<SmpSummary> summaryTop10List = null;
        if ("691948539811991711".equals(type)) {
            summaryTop10List = summaryData.stream().filter(smpSummary -> smpSummary.getObjId() != null)
                    .sorted(Comparator.comparing(SmpSummary::getXh).reversed())
                    .limit(20)
                    .collect(Collectors.toList());
        }
        if ("691948539811991712".equals(type)) {
            summaryTop10List = summaryData.stream().filter(smpSummary -> smpSummary.getObjId() != null)
                    .sorted(Comparator.comparing(SmpSummary::getXh).reversed())
                    .limit(10)
                    .collect(Collectors.toList());
        }

        //summaryData对datasource去重
//        List<SmpSummary> summaryList = summaryTop10List.stream().map(smpSummary -> {
//            String[] ds = smpSummary.getDataSource().split("，");
//            if (ds.length > 1) {
//
//            }
//
//        }).collect(Collectors.toList());

        List<SmpSummary> summaryList = summaryTop10List.stream()
                .peek(smpSummary -> {
                    String datasource = Arrays.stream(smpSummary.getDataSource().split("、")).distinct().collect(Collectors.joining("、"));
                    smpSummary.setDataSource(datasource);
                })
                .collect(Collectors.toList());

        //2,组装统计表
//        List<StatisticsVo> statisticsVoList = reportMapper.getStatisticsMap(company_id, typecode, voltage);
//        List<String> idList = summaryData.stream().filter(smpSummary -> smpSummary.getObjId() != null).limit(10).map(SmpSummary::getObjId).collect(Collectors.toList());
        List<String> idList = summaryList.stream().map(SmpSummary::getObjId).collect(Collectors.toList());

        List<StatisticsVo> statisticsVoList = new ArrayList<StatisticsVo>();
        if(idList!=null && idList.size()>0) {
            statisticsVoList = reportMapper.getStatisticsMapByTen(idList);
        }

        //3,组装明细表，根据汇总的前十条
        ReportPartVO reportPartVO = ReportPartVO.builder()
                .summaries(summaryList)
                .statisticsMap(statisticsVoList)
                .infoList(summaryList.stream() //组装前十条的明细
                        .map(this::getInfoDetailList)
                        .collect(Collectors.toList()))
                .voltage(voltage)
                .typecode(typecode)
                .title(typecode+voltage)
                .build();

        return reportPartVO;
    }

    /**
     * 拿到一个设备的详细明细
     * @return 一种设备的一条详细描述 例如滁州35kv变压器的汇总第1条的详细描述
     */
    @Override
    public String getInfoDetailList(SmpSummary smpSummaries) {
        //1，根据判别类型定义模板
        //        XXX供电公司XX变电站的2#主变，容量50MVA，
//        01月10日整点的最大有功时刻和功率为19时（50MW），
//        负载率为100%，高于80%，判定该变压器重载。
        String[] splitJudgeType = smpSummaries.getJudgeType().split("、");
        StringBuilder sb = new StringBuilder();
        String psrType = smpSummaries.getPsrType();
        String voltage = smpSummaries.getVoltage();
        sb.append(smpSummaries.getCompanyName());//拼接单位
        //模板
//        ConstatUtil.UNDERLINE_START;
//        ConstatUtil.UNDERLINE_END
//        //主变重载
//        String zbZZStr = "容量${cap}MVA，${monthDay}整点的最大有功时刻和功率为${hour}时(${p})，负载率为${loadRate}，高于80%，判定变压器重载。";
//        //主变重损
//        String zbZSStr = "2020年7月24日理论线损计算该变压器有功供电量${supplyEle}MWh，损失电量${lossEle}MWh，技术线损率${lineLossRate}%，高于1%，且变压器铜损${copperLoss}MWh，铁损${ironLoss}，MWh，铜铁损比为${copperIconRate}，高于1，判定该变压器重损。";
//        //主变持续重载
//        String zbCXStr = "容量为${cap}MVA，${subStrList} 均高于80%，判定该变压器持续重载。";
//        //主变持续重载子串
//        String zbCXSubStr = "${startTime}至${endTime}整点最大有功时刻和功率分别为${timeAndRate}，最大负载率分别为${loadRateStr}，";
//        //输电线路重载
//        String lineZZStr = "导线型号为${lineType}，线路在20℃热稳定电流为${rating}A，${maxDate}最大电流时刻和电流为${maxHour}时（${maxI}A），最大负载率${maxLoadRate}%，高于70%，判定该线路疑似重载。";
//        //输电线路重损
//        String lineZsStr = "07月24日理论线损计算该线路有功供电量${supplyEle}MWh，理论损失电量${lossEle}MWh，技术线损率${lossRate}%，高于1%，判定该线路重损。";
//        //输电线路持续重载
//        String lineCXStr = "导线型号为${lineType}，线路在20℃热稳定电流为${rating}A，${lineCxStrList}判定该线路持续重载。";
//        //输电线路持续重载子串
//        String lineCxStrSub = "${startDate}至${endDate}日的最大电流时刻和电流分别为${hourAndEleStr}，最大负载率分别为${loadRateStr}，均高于70%，";
//        //配线重载
//        String distLineZZtr = "导线型号为${lineType}，线路在20℃热稳定电流为${rating}A，${maxDate}最大电流时刻和电流为${maxHour}时（${maxI}A），最大负载率${maxLoadRate}%，高于70%，判定该线路疑似重载。";
//        //配线重损
//        String distLineZSStr = "07月24日理论线损计算该线路有功供电量${supplyEle}MWh，理论损失电量${lossEle}MWh，技术线损率${lossRate}%，高于2%，判定该线路重损。";
//        //配线持续重载
//        String distLineCXStr = "导线型号为${lineType}，线路在20℃热稳定电流为${rating}A，${lineCxStrList}判定该线路持续重载。";
//        //配线持续重载子串
//        String distLineCxStrSub = "${startDate}至${endDate}日的最大电流时刻和电流分别为${hourAndEleStr}，最大负载率分别为${loadRateStr}，均高于70%，";
//        //配变重载
//        String distTranZZStr= "型号为${tranType}，${maxDate}整点的最大有功时刻和有功为${maxHour}时（${maxRating}MW），负载率为${loadRate}%，高于80%，判定该变压器重载。";
//        //配变持续重载
//        String distTranZCStr = "型号为${lineType}，${distTranZCStrSub}均高于80%，判定该变压器持续重载。";
//        //配变持续重载子串
//        String distTranZCStrSub = "${startTime}至${endTime}整点最大有功时刻和有功分别为${timeAndRate}，最大负载率分别为${loadRateStr}，";
//        //导线过长
//        String lineTooLongStr = "${lineName}线路，供电区域为${supplyArea}，线路长度${lineLength}km，超出标准值40km，判定该线路长度超标。";
//        //导线截面异常
//        String lineRadiusStr = "该线路下架空线路截面${radiusOver}，不在截面标准(70、95、120、150、185、240)范围内，判定该线路存在导线截面异常。";
//        String lineRadiusEleStr = "该线路下电缆线路截面${eleOver}，不在截面标准(500、400、300、240、185、150、120、70)范围内，判定该线路存在导线截面异常。";
//        String lineRadiusAndELeStr ="该线路下架空线路截面${radiusOver}，不在截面标准(70、95、120、150、185、240)范围内，电缆线路截面${eleOver}，不在截面标准(500、400、300、240、185、150、120、70)范围内，判定该线路存在导线截面异常。";
//        //高耗能
//        String highPowerStr = "型号为${distTranType}，该型号为建议淘汰型号，判定该变压器高耗能变压器。";
//        //三项不平衡
//        String threeBalance = "${month}月存在${count}日三相不平衡越限，越限日为${date}，判定该变压器三相不平衡超限。";
        String zbZZStr = "容量"+ConstatUtil.UNDERLINE_START+"${cap}"+ConstatUtil.UNDERLINE_END+"MVA，"+ConstatUtil.UNDERLINE_START+"${monthDay}"+ConstatUtil.UNDERLINE_END+"整点的最大有功时刻和功率为"+ConstatUtil.UNDERLINE_START+"${hour}"+ConstatUtil.UNDERLINE_END+"("+ConstatUtil.UNDERLINE_START+"${p}"+ConstatUtil.UNDERLINE_END+"MW)，负载率为"+ConstatUtil.UNDERLINE_START+"${loadRate}"+"%"+ConstatUtil.UNDERLINE_END+"，高于80%，判定变压器"+ConstatUtil.RED_START+"重载"+ConstatUtil.RED_END+"。";
//主变重损
        String zbZSStr = "2020年7月24日理论线损计算该变压器有功供电量"+ConstatUtil.UNDERLINE_START+"${supplyEle}"+ConstatUtil.UNDERLINE_END+"MWh，损失电量"+ConstatUtil.UNDERLINE_START+"${lossEle}"+ConstatUtil.UNDERLINE_END+"MWh，技术线损率"+ConstatUtil.UNDERLINE_START+"${lineLossRate}"+ConstatUtil.UNDERLINE_END+"%，高于1%，且变压器铜损"+ConstatUtil.UNDERLINE_START+"${copperLoss}"+ConstatUtil.UNDERLINE_END+"MWh，铁损"+ConstatUtil.UNDERLINE_START+"${ironLoss}"+ConstatUtil.UNDERLINE_END+"%"+ConstatUtil.UNDERLINE_END+"，MWh，铜铁损比为"+ConstatUtil.UNDERLINE_START+"${copperIconRate}"+ConstatUtil.UNDERLINE_END+"，高于1，判定该变压器"+ConstatUtil.RED_START+"重损"+ConstatUtil.RED_END+"。";
//主变持续重载
        String zbCXStr = "容量为"+ConstatUtil.UNDERLINE_START+"${cap}"+ConstatUtil.UNDERLINE_END+"MVA，"+ConstatUtil.UNDERLINE_START+"${subStrList}"+ConstatUtil.UNDERLINE_END+" 均高于80%，判定该变压器"+ConstatUtil.RED_START+"持续重载"+ConstatUtil.RED_END+"。";
//主变持续重载子串
        String zbCXSubStr = ""+ConstatUtil.UNDERLINE_START+"${startTime}"+ConstatUtil.UNDERLINE_END+"至"+ConstatUtil.UNDERLINE_START+"${endTime}"+ConstatUtil.UNDERLINE_END+"整点最大有功时刻和功率分别为"+ConstatUtil.UNDERLINE_START+"${timeAndRate}"+ConstatUtil.UNDERLINE_END+"，最大负载率分别为"+ConstatUtil.UNDERLINE_START+"${loadRateStr}"+ConstatUtil.UNDERLINE_END+"，";
//输电线路重载
        String lineZZStr = "导线型号为"+ConstatUtil.UNDERLINE_START+"${lineType}"+ConstatUtil.UNDERLINE_END+"，线路在20℃热稳定电流为"+ConstatUtil.UNDERLINE_START+"${rating}"+ConstatUtil.UNDERLINE_END+"A，"+ConstatUtil.UNDERLINE_START+"${maxDate}"+ConstatUtil.UNDERLINE_END+"最大电流时刻和电流为"+ConstatUtil.UNDERLINE_START+"${maxHour}"+ConstatUtil.UNDERLINE_END+"时（"+ConstatUtil.UNDERLINE_START+"${maxI}"+ConstatUtil.UNDERLINE_END+"A），最大负载率"+ConstatUtil.UNDERLINE_START+"${maxLoadRate}"+ConstatUtil.UNDERLINE_END+"%，高于70%，判定该线路"+ConstatUtil.RED_START+"重载"+ConstatUtil.RED_END+"。";
//输电线路重损
        String lineZsStr = "07月24日理论线损计算该线路有功供电量"+ConstatUtil.UNDERLINE_START+"${supplyEle}"+ConstatUtil.UNDERLINE_END+"MWh，理论损失电量"+ConstatUtil.UNDERLINE_START+"${lossEle}"+ConstatUtil.UNDERLINE_END+"MWh，技术线损率"+ConstatUtil.UNDERLINE_START+"${lossRate}"+ConstatUtil.UNDERLINE_END+"%，高于1%，判定该线路"+ConstatUtil.RED_START+"重损"+ConstatUtil.RED_END+"。";
//输电线路持续重载
        String lineCXStr = "导线型号为"+ConstatUtil.UNDERLINE_START+"${lineType}"+ConstatUtil.UNDERLINE_END+"，线路在20℃热稳定电流为"+ConstatUtil.UNDERLINE_START+"${rating}"+ConstatUtil.UNDERLINE_END+"A，"+ConstatUtil.UNDERLINE_START+"${lineCxStrList}"+ConstatUtil.UNDERLINE_END+"判定该线路"+ConstatUtil.RED_START+"持续重载"+ConstatUtil.RED_END+"。";
//输电线路持续重载子串
        String lineCxStrSub = ""+ConstatUtil.UNDERLINE_START+"${startDate}"+ConstatUtil.UNDERLINE_END+"至"+ConstatUtil.UNDERLINE_START+"${endDate}"+ConstatUtil.UNDERLINE_END+"的最大电流时刻和电流分别为"+ConstatUtil.UNDERLINE_START+"${hourAndEleStr}"+ConstatUtil.UNDERLINE_END+"，最大负载率分别为"+ConstatUtil.UNDERLINE_START+"${loadRateStr}"+ConstatUtil.UNDERLINE_END+"，均高于70%，";
//配线重载
        String distLineZZtr = "导线型号为"+ConstatUtil.UNDERLINE_START+"${lineType}"+ConstatUtil.UNDERLINE_END+"，线路在20℃热稳定电流为"+ConstatUtil.UNDERLINE_START+"${rating}"+ConstatUtil.UNDERLINE_END+"A，"+ConstatUtil.UNDERLINE_START+"${maxDate}"+ConstatUtil.UNDERLINE_END+"最大电流时刻和电流为"+ConstatUtil.UNDERLINE_START+"${maxHour}"+ConstatUtil.UNDERLINE_END+"时（"+ConstatUtil.UNDERLINE_START+"${maxI}"+ConstatUtil.UNDERLINE_END+"A），最大负载率"+ConstatUtil.UNDERLINE_START+"${maxLoadRate}"+ConstatUtil.UNDERLINE_END+"%，高于70%，判定该线路"+ConstatUtil.RED_START+"重载"+ConstatUtil.RED_END+"。";
//配线重损
        String distLineZSStr = "07月24日理论线损计算该线路有功供电量"+ConstatUtil.UNDERLINE_START+"${supplyEle}"+ConstatUtil.UNDERLINE_END+"MWh，理论损失电量"+ConstatUtil.UNDERLINE_START+"${lossEle}"+ConstatUtil.UNDERLINE_END+"MWh，技术线损率"+ConstatUtil.UNDERLINE_START+"${lossRate}"+ConstatUtil.UNDERLINE_END+"%，高于2%，判定该线路"+ConstatUtil.RED_START+"重损"+ConstatUtil.RED_END+"。";
//配线持续重载
        String distLineCXStr = "导线型号为"+ConstatUtil.UNDERLINE_START+"${lineType}"+ConstatUtil.UNDERLINE_END+"，线路在20℃热稳定电流为"+ConstatUtil.UNDERLINE_START+"${rating}"+ConstatUtil.UNDERLINE_END+"A，"+ConstatUtil.UNDERLINE_START+"${lineCxStrList}"+ConstatUtil.UNDERLINE_END+"判定该线路"+ConstatUtil.RED_START+"持续重载"+ConstatUtil.RED_END+"。";
//配线持续重载子串
        String distLineCxStrSub = ""+ConstatUtil.UNDERLINE_START+"${startDate}"+ConstatUtil.UNDERLINE_END+"至"+ConstatUtil.UNDERLINE_START+"${endDate}"+ConstatUtil.UNDERLINE_END+"的最大电流时刻和电流分别为"+ConstatUtil.UNDERLINE_START+"${hourAndEleStr}"+ConstatUtil.UNDERLINE_END+"，最大负载率分别为"+ConstatUtil.UNDERLINE_START+"${loadRateStr}"+ConstatUtil.UNDERLINE_END+"，均高于70%，";
//配变重载
        String distTranZZStr= "型号为"+ConstatUtil.UNDERLINE_START+"${tranType}"+ConstatUtil.UNDERLINE_END+"，"+ConstatUtil.UNDERLINE_START+"${maxDate}"+ConstatUtil.UNDERLINE_END+"整点的最大有功时刻和有功为"+ConstatUtil.UNDERLINE_START+"${maxHour}"+ConstatUtil.UNDERLINE_END+"时（"+ConstatUtil.UNDERLINE_START+"${maxRating}"+ConstatUtil.UNDERLINE_END+"MW），负载率为"+ConstatUtil.UNDERLINE_START+"${loadRate}"+ConstatUtil.UNDERLINE_END+"%，高于80%，判定该变压器"+ConstatUtil.RED_START+"重载"+ConstatUtil.RED_END+"。";
//配变持续重载
        String distTranZCStr = "型号为"+ConstatUtil.UNDERLINE_START+"${lineType}"+ConstatUtil.UNDERLINE_END+"，"+ConstatUtil.UNDERLINE_START+"${distTranZCStrSub}"+ConstatUtil.UNDERLINE_END+"均高于80%，判定该变压器"+ConstatUtil.RED_START+"持续重载"+ConstatUtil.RED_END+"。";
//配变持续重载子串
        String distTranZCStrSub = ""+ConstatUtil.UNDERLINE_START+"${startTime}"+ConstatUtil.UNDERLINE_END+"至"+ConstatUtil.UNDERLINE_START+"${endTime}"+ConstatUtil.UNDERLINE_END+"整点最大有功时刻和有功分别为"+ConstatUtil.UNDERLINE_START+"${timeAndRate}"+ConstatUtil.UNDERLINE_END+"，最大负载率分别为"+ConstatUtil.UNDERLINE_START+"${loadRateStr}"+ConstatUtil.UNDERLINE_END+"，";
//导线过长
        String lineTooLongStr = ""+ConstatUtil.UNDERLINE_START+"${lineName}"+ConstatUtil.UNDERLINE_END+"线路，供电区域为"+ConstatUtil.UNDERLINE_START+"${supplyArea}"+ConstatUtil.UNDERLINE_END+"，线路长度"+ConstatUtil.UNDERLINE_START+"${lineLength}"+ConstatUtil.UNDERLINE_END+"km，超出标准值40km，判定该线路"+ConstatUtil.RED_START+"长度超标"+ConstatUtil.RED_END+"。";
//导线截面异常
        String lineRadiusStr = "该线路下架空线路截面"+ConstatUtil.UNDERLINE_START+"${radiusOver}"+ConstatUtil.UNDERLINE_END+"，不在截面标准(70、95、120、150、185、240)范围内，判定该线路存在导线截面异常。";
        String lineRadiusEleStr = "该线路下电缆线路截面"+ConstatUtil.UNDERLINE_START+"${eleOver}"+ConstatUtil.UNDERLINE_END+"，不在截面标准(500、400、300、240、185、150、120、70)范围内，判定该线路存在导线截面异常。";
        String lineRadiusAndELeStr ="该线路下架空线路截面"+ConstatUtil.UNDERLINE_START+"${radiusOver}"+ConstatUtil.UNDERLINE_END+"，不在截面标准(70、95、120、150、185、240)范围内，电缆线路截面"+ConstatUtil.UNDERLINE_START+"${eleOver}"+ConstatUtil.UNDERLINE_END+"，不在截面标准(500、400、300、240、185、150、120、70)范围内，判定该线路存在导线截面异常。";
//高耗能
        String highPowerStr = "型号为"+ConstatUtil.UNDERLINE_START+"${distTranType}"+ConstatUtil.UNDERLINE_END+"，投运日期"+ConstatUtil.UNDERLINE_START+"${runDate}"+ConstatUtil.UNDERLINE_END+"，该型号为建议淘汰型号，判定该变压器"+ConstatUtil.RED_START+"高耗能变压器"+ConstatUtil.RED_END+"。";
//三项不平衡
        String threeBalance = ""+ConstatUtil.UNDERLINE_START+"${month}"+ConstatUtil.UNDERLINE_END+"月存在"+ConstatUtil.UNDERLINE_START+"${count}"+ConstatUtil.UNDERLINE_END+"日三相不平衡越限，越限日为"+ConstatUtil.UNDERLINE_START+"${date}"+ConstatUtil.UNDERLINE_END+"，判定该变压器"+ConstatUtil.RED_START+"三相不平衡超限"+ConstatUtil.RED_END+"。";
        Template template = null;
        Configuration configuration = new Configuration(new Version("2.3.23"));
        try {
            if( "DFPowerTransformer".equals(psrType) ) { //拼接设备的名称--主变和配变
                String str = "";
                if (smpSummaries.getSubName().contains("变电站")) {
                    str = smpSummaries.getSubName()+"的"+smpSummaries.getPsrName()+"，";
                }else{
                    str = smpSummaries.getSubName()+"变电站的"+smpSummaries.getPsrName()+"，";
                }

                sb.append(str);
            } else if ("DFLine".equals(psrType) ) {
                String str = smpSummaries.getPsrName()+"，";
                sb.append(str);
            } else if("DFDistributionLine".equals(psrType) && !smpSummaries.getJudgeType().equals("导线截面异常")){
                String str = smpSummaries.getPsrName()+"，";
                sb.append(str);
            } else if("DFDistributionLine".equals(psrType) && smpSummaries.getJudgeType().equals("导线截面异常")){
                String str = smpSummaries.getSubName()+"变电站的"+smpSummaries.getPsrName()+"，";
                sb.append(str);
            } else if ("DFDistributionTransformer".equals(psrType)) {
                String str = smpSummaries.getPsrName() + "，";
                sb.append(str);
            }
//

            for (String judgeType : splitJudgeType) {
                if(judgeType.equals("重载") && "DFPowerTransformer".equals(psrType)  ) {//重载变压器
                    template = new Template("zbzz", zbZZStr, configuration);
                    StringWriter result = new StringWriter();
                    List<TranLoadVO> tranLoad = reportMapper.getTranLoad(smpSummaries.getObjId());

                    Map map = new HashMap();
                    map.put("cap", tranLoad.get(0).getCap());
                    map.put("monthDay", tranLoad.get(0).getMaxTime());
                    map.put("hour", tranLoad.get(0).getPTime());
                    map.put("p", tranLoad.get(0).getP());
                    map.put("loadRate", tranLoad.get(0).getLoadRate());

                    template.process(map, result);
                    sb.append(result.toString());
                }else if(judgeType.equals("重损") && "DFPowerTransformer".equals(psrType)){ //重损变压器
                    template = new Template("zbzs", zbZSStr, configuration);
                    StringWriter  result = new StringWriter();
                    TranLossVo tranLossVO = reportMapper.getTranLossVO(smpSummaries.getObjId());
                    Map map = new HashMap();
                    map.put("supplyEle", tranLossVO.getSupplyEle());
                    map.put("lossEle", tranLossVO.getLossEle());
                    map.put("lineLossRate", tranLossVO.getLineLossRate());
                    map.put("copperLoss", tranLossVO.getCopperLoss());
                    map.put("ironLoss", tranLossVO.getIronLoss());
                    map.put("copperIconRate", tranLossVO.getCopperIconRate());
                    template.process(map, result);
                    sb.append(result.toString());
                }else if(judgeType.equals("持续重载") && "DFPowerTransformer".equals(psrType)){
                    List<TranLoadAlwaysVO> voList = reportMapper.getTranAlwaysLoad(smpSummaries.getObjId());
                    template = new Template("zbcx", zbCXStr, configuration);
                    StringWriter  result = new StringWriter();
                    HashMap<String, String> hashMap = new HashMap<>();
                    StringBuilder builder =  new StringBuilder();
                    for (TranLoadAlwaysVO tranAlwaysLoad : voList) {
                        Template templateSub =new Template("zbCXSub", zbCXSubStr, configuration);
                        StringWriter  resultSub = new StringWriter();
                        Map map = new HashMap();
                        hashMap.put("cap", tranAlwaysLoad.getCap());
                        map.put("startTime", tranAlwaysLoad.getStartTime());
                        map.put("endTime", tranAlwaysLoad.getEndTime());
                        map.put("timeAndRate", tranAlwaysLoad.getTimeAndRate());
                        map.put("loadRateStr", tranAlwaysLoad.getLoadRateStr());
                        templateSub.process(map, resultSub);
                        builder.append(resultSub.toString());
                    }
                    hashMap.put("subStrList",builder.toString());
                    template.process(hashMap,result);

                    sb.append(result.toString());
                }else if(judgeType.equals("重载") && "DFLine".equals(psrType)){
                    template = new Template("linezz", lineZZStr, configuration);
                    LineTranVO lineTranVO = reportMapper.getLineTranVO(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("rating", lineTranVO.getRating());
                    map.put("maxDate", lineTranVO.getMaxDate());
                    map.put("maxHour", lineTranVO.getMaxHour());
                    map.put("maxI", lineTranVO.getMaxI());
                    map.put("maxLoadRate", lineTranVO.getMaxLoadRate());
                    map.put("lineType", lineTranVO.getLineType());
                    template.process(map, result);
                    sb.append(result.toString());
                }else if("重损".equals(judgeType) && "DFLine".equals(psrType)){
                    template = new Template("lineZsStr", lineZsStr, configuration);
                    LineLossVo vo = reportMapper.getLineLossVO(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("supplyEle", vo.getSupplyEle());
                    map.put("lossEle", vo.getLossEle());
                    map.put("lossRate", vo.getLossRate());
                    template.process(map, result);
                    sb.append(result.toString());

                }else if("持续重载".equals(judgeType) && "DFLine".equals(psrType)){
                    List<LineAlwaysLoadVO> lineAlwaysVo = reportMapper.getLineAlwaysVo(smpSummaries.getObjId());
                    template = new Template("lineCx", lineCXStr, configuration);
                    StringWriter  result = new StringWriter();
                    HashMap<String, String> hashMap = new HashMap<>();
                    StringBuilder builder =  new StringBuilder();
                    for (LineAlwaysLoadVO vo : lineAlwaysVo) {
                        Template templateSub =new Template("lineCXSub", lineCxStrSub, configuration);
                        StringWriter  resultSub = new StringWriter();
                        Map map = new HashMap();
                        hashMap.put("rating", vo.getRating());
                        hashMap.put("lineType", vo.getLineType());
                        map.put("startDate", vo.getStartDate());
                        map.put("endDate", vo.getEndDate());
                        map.put("hourAndEleStr", vo.getHourAndEleStr());
                        map.put("loadRateStr", vo.getLoadRateStr());
                        templateSub.process(map, resultSub);
                        builder.append(resultSub.toString());
                    }
                    hashMap.put("lineCxStrList",builder.toString());
                    template.process(hashMap,result);
                    sb.append(result.toString());
                }else if ("重载".equals(judgeType) && "DFDistributionLine".equals(psrType)){
                    template = new Template("distLineZZtr", distLineZZtr, configuration);
                    DistLineLoadVO vo = reportMapper.getDistLoadVo(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("rating", vo.getRating());
                    map.put("maxDate", vo.getMaxDate());
                    map.put("maxHour", vo.getMaxHour());
                    map.put("maxI", vo.getMaxI());
                    map.put("lineType",vo.getLineType());
                    map.put("maxLoadRate", vo.getMaxLoadRate());
                    template.process(map, result);
                    sb.append(result.toString());
                }else if("重损".equals(judgeType) && "DFDistributionLine".equals(psrType)){
                    template = new Template("distLineZSStr", distLineZSStr, configuration);
                    DistLineLossVO vo = reportMapper.getDistLineLossVO(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("supplyEle", vo.getSupplyEle());
                    map.put("lossEle", vo.getLossEle());
                    map.put("lossRate", vo.getLossRate());
                    template.process(map, result);
                    sb.append(result.toString());
                } else if ("持续重载".equals(judgeType) && "DFDistributionLine".equals(psrType)) {
                    List<DistLineAlwaysLoadVo> vos = reportMapper.getDistLineAlwaysVO(smpSummaries.getObjId());
                    template = new Template("distLineCx",distLineCXStr , configuration);
                    StringWriter  result = new StringWriter();
                    HashMap<String, String> hashMap = new HashMap<>();
                    StringBuilder builder =  new StringBuilder();

                    for (DistLineAlwaysLoadVo vo : vos) {
                        Template templateSub =new Template("lineCXSub", distLineCxStrSub, configuration);
                        StringWriter  resultSub = new StringWriter();
                        Map map = new HashMap();
                        hashMap.put("rating", vo.getRating());
                        hashMap.put("lineType", vo.getLineType());
                        map.put("startDate", vo.getStartTime());
                        map.put("endDate", vo.getEndTime());
                        map.put("hourAndEleStr", vo.getHourAndEleStr());
                        map.put("loadRateStr", vo.getLoadRateStr());
                        templateSub.process(map, resultSub);
                        builder.append(resultSub.toString());
                    }
                    hashMap.put("lineCxStrList",builder.toString());
                    template.process(hashMap,result);
                    sb.append(result.toString());
                }else if("重载".equals(judgeType) && "DFDistributionTransformer".equals(psrType)){
                    template = new Template("distTranZZStr", distTranZZStr, configuration);
                    DistTranLoadVO vo = reportMapper.getDistTranLoadVO(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("maxDate", vo.getMaxDate());
                    map.put("maxHour", vo.getMaxHour());
                    map.put("maxRating", vo.getMaxRating());
                    map.put("loadRate", vo.getLoadRate());
                    map.put("tranType",vo.getTranType());
                    template.process(map, result);
                    sb.append(result.toString());
                }else if("持续重载".equals(judgeType) && "DFDistributionTransformer".equals(psrType)){
                    List<DistTranLoadAlwaysVO> vos = reportMapper.getDistTranLoadAlwaysVO(smpSummaries.getObjId());
                    template = new Template("distTranZCStr",distTranZCStr , configuration);
                    StringWriter  result = new StringWriter();
                    HashMap<String, String> hashMap = new HashMap<>();
                    StringBuilder builder =  new StringBuilder();

                    for (DistTranLoadAlwaysVO vo : vos) {
                        Template templateSub =new Template("distTranZCStrSub", distTranZCStrSub, configuration);
                        StringWriter  resultSub = new StringWriter();
                        Map map = new HashMap();
                        hashMap.put("lineType", vo.getLineType());
                        map.put("startDate", vo.getStartTime());
                        map.put("endDate", vo.getEndTime());
                        map.put("timeAndRate", vo.getTimeAndRate());
                        map.put("loadRateStr", vo.getLoadRateStr());
                        templateSub.process(map, resultSub);
                        builder.append(resultSub.toString());
                    }
                    hashMap.put("distTranZCStrSub",builder.toString());
                    template.process(hashMap,result);
                    sb.append(result.toString());
                }else if(judgeType.equals("风害") && "DFLine".equals(psrType)){
                    template = new Template("wind", WIND_TEMPLATE, configuration);
                    Map<String, String> windWirePoleMap = datService.getWindWirePoleMapByObjId(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    template.process(windWirePoleMap, result);
                    sb.append(result.toString());
                }else if(judgeType.equals("污闪") && "DFLine".equals(psrType)){
                    template = new Template("pollution", POLLUTION_TEMPLATE, configuration);
                    Map<String, String> pollutionsInsulatorMap = datService.getPollutionsInsulatorMapByObjId(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    template.process(pollutionsInsulatorMap, result);
                    sb.append(result.toString());
                }else if(judgeType.equals("老旧") && "DFLine".equals(psrType)){
                    template = new Template("old", OLD_TEMPLATE, configuration);
                    Map<String, String> oldWirePoleMap = datService.getOldWirePoleMapByObjId(smpSummaries.getObjId());
                    StringWriter result = new StringWriter();
                    template.process(oldWirePoleMap, result);
                    sb.append(result.toString());
                }else if(judgeType.equals("导线过长")){
                    TooLongLineVO vo = reportMapper.getTooLongLineVo(smpSummaries.getObjId());
                    template = new Template("lineTooLongStr", lineTooLongStr, configuration);
                    StringWriter  result = new StringWriter();
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("lineName", vo.getLineName());
                    hashMap.put("supplyArea", vo.getSupplyArea());
                    hashMap.put("lineLength", vo.getLineLength());
                    template.process(hashMap,result);
                    sb.append(result.toString());
                } else if (judgeType.equals("导线截面异常")) {
                    LineRadiusVO vo = reportMapper.getLineRadiusVO(smpSummaries.getObjId());
                    String realStr = "";
                    HashMap<String, String> hashMap = new HashMap<>();

                    if (vo.getRadiusOver() == null) {
                        realStr = lineRadiusEleStr;
                        hashMap.put("eleOver", vo.getEleOver());
                    }else if (vo.getEleOver() == null) {
                        realStr = lineRadiusStr;
                        hashMap.put("radiusOver", vo.getRadiusOver());
                    }else {
                        realStr = lineRadiusAndELeStr;
                        hashMap.put("eleOver", vo.getEleOver());
                        hashMap.put("radiusOver", vo.getRadiusOver());
                    }
                    template = new Template("lineRadiusStr", realStr, configuration);
                    StringWriter  result = new StringWriter();

                    template.process(hashMap,result);
                    sb.append(result.toString());
                } else if (judgeType.equals("高耗能变压器") && "DFDistributionTransformer".equals(psrType)) {
                    HighPowerVO vo = reportMapper.getHighPowerVO(smpSummaries.getObjId());
                    template = new Template("highPowerStr", highPowerStr, configuration);
                    StringWriter  result = new StringWriter();
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("distTranType", vo.getDistTranType());
                    hashMap.put("runDate", vo.getRunDate());
                    template.process(hashMap,result);
                    sb.append(result.toString());
                } else if (judgeType.equals("三相不平衡超限") && "DFDistributionTransformer".equals(psrType)) {
                    List<String> list = reportMapper.getThreeBlanceDate(smpSummaries.getObjId());
                    Map<String, String> detail = getDetailThreeBlace(list);
                    template = new Template("threeBalance", threeBalance, configuration);
                    StringWriter  result = new StringWriter();

                    template.process(detail,result);
                    sb.append(result.toString());
                }
            }

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }


        return sb.toString();
    }


    /**
     * @description 根据传入的SmpSummary的objid
     * @author: GuoZheng
     * @create 2021-01-17 18:20
     */
    @Override
    public List<Map<String, String>> getInfoDetailList(String objId) {
        //组装其他


        //风害
        Map<String, String> windWirePoleMap = datService.getWindWirePoleMapByObjId(objId);

        //绝缘子水平下降的明细
        Map<String, String> insulatorMap = datService.getPollutionsInsulatorMapByObjId(objId);

        //老旧
        Map<String, String> oldWirePoleMap = datService.getOldWirePoleMapByObjId(objId);

//        测试结果:
//        [{}, {pollutionInsulators={"standardDistance":"30","wirePoleNames":"#007,#006,#001","companyName":"合肥供电公司","wirePoleNOs":"#007,#006,#001","lineName":"220kV常贾2C76线","regionCodes":"30.0","insulatorNames":"FXBW-220/120,FXBW-220/120,XP-70","creepageDistance":"28.8mm/kV,28.8mm/kV,29.1mm/kV","regionMaxCode":"30.0"}}, {oldWirePoles={"runDate":"1984年05月01日,1984年05月01日,1984年05月01日","wirePoleNames":"#002,#003,#011","companyName":"合肥供电公司","wirePoleNOs":"#002,#003,#011","lineName":"220kV常贾2C76线","expirationDate":"2004年05月01日,2004年05月01日,2004年05月01日"}}]
//         注意:空括号防风
        return Arrays.asList(windWirePoleMap, insulatorMap, oldWirePoleMap);
    }

    @Override
    public Integer summaryData(String company_id) {
//        //汇总数据，同时刷新id
//        String companyName = constatUtil.getCityNameById(company_id);
//        reportMapper.updateDatInsulatorCompany(company_id, companyName);
//        reportMapper.updateDatWirepoleOledCompany(company_id, companyName);
//        reportMapper.updateDatWirepoleWindCompany(company_id, companyName);
//        reportMapper.updateLmsDistdetailCompany(company_id, companyName);
//        reportMapper.updateLmsLinedetailCompany(company_id, companyName);
//        reportMapper.updateLmsTrandetailCompany(company_id, companyName);
//        reportMapper.updateLltweightLossLineCompany(company_id, companyName);
//        reportMapper.updateLltweightLossTranCompany(company_id, companyName);
        //插入之前先清空本单位的汇总数据
        smpSummaryMapper.deleteByCompanyId(company_id);
        //插入汇总表
        int i = reportMapper.insertSummar(company_id);

        //处理汇总表的序号
//        List<SmpSummary> list = smpSummaryMapper.findAll();
//        for (int i = 0; i < list.size(); i++) {
//            int id = i + 1;
//            list.get(i).setId(String.valueOf(id));
//        }
//        smpSummaryMapper.insertList(list);
        return i;
    }



    /**
     * 测试模板文字
     * @return
     */
//    public String getInfo() {
//
//        String str = "";
//        //主变重载数据
////        reportMapper.getTranLoad();
//
////        XXX供电公司XX变电站的2#主变，容量50MVA，
////        01月10日整点的最大有功时刻和功率为19时（50MW），
////        负载率为100%，高于80%，判定该变压器重载。
//        Template template = null;
//        Configuration configuration = new Configuration(new Version("2.3.23"));
//        try {
//            Map map = new HashMap();
//            map.put("name", "张三");
//            map.put("money", 10.155);
//            map.put("point", 10);
//
//             template = new Template("strTpl", "您好${name}，晚上好！" +
//                    "您目前余额：${money?string(\"#.##\")}元，" +
//                    "积分：${point}", configuration);
//            StringWriter result = new StringWriter();
//            template.process(map, result);
//            str = result.toString();
//
//            String newStr = "aa:${aa},bb:${bb}";
//            template = new Template("11",newStr,configuration);
//            StringWriter result2 = new StringWriter();
//            template.process(Map.of("aa","aa","bb","bb"),result2);
//            str = str + result2.toString();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        List<SmpSummary> summaryData = reportMapper.getSummaryData("773222052638515200", "DFDistributionTransformer", "10").stream().filter(smpSummary ->
//             smpSummary.getJudgeType().equals("重载")).collect(Collectors.toList());
//        return getInfoDetailList(summaryData.get(0));
////        return null;
//    }

    /**
     * 三象不平衡超限
     * @param list
     * @return
     */
    private Map<String,String> getDetailThreeBlace(List<String> list) {
        List<String> collect = list.stream().sorted().collect(Collectors.toList());
        HashMap<String, String> map = new HashMap<>();
        map.put("count", String.valueOf(list.size()));
        map.put("month", list.get(0).substring(4,6));
        StringBuilder sb = new StringBuilder();
        for (String s : collect) {
            sb.append(s.substring(s.length() - 2)).append("日、");
        }
        map.put("date", sb.substring(0, sb.length() - 1));
        return map;
    }

}
